package com.daidai.activitys

import android.os.Build
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.daidai.base.BaseActivity
import com.daidai.tools.G
import com.daidai.spinner.R
import kotlinx.coroutines.*
import java.time.Instant
import kotlin.coroutines.CoroutineContext

class CoroActivity() : BaseActivity(),CoroutineScope {

    lateinit var tvText:TextView
    lateinit var tvWork1:TextView
    lateinit var tvWork2:TextView

    lateinit  var job: Job
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun getContentViewResId() = R.layout.activity_coroutine

    override fun initView() {
        tvText = findViewById(R.id.tvText)
        tvWork1 = findViewById(R.id.tvWork1)
        tvWork2 = findViewById(R.id.tvWork2)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initData() {
        job = Job()
        loadDataFromUI()
        delayLoad()
    }

    override fun onDestroy() {
        job.cancel()
        // 当 Activity 销毁的时候取消该 Scope 管理的 job。
        // 这样在该 Scope 内创建的子 Coroutine 都会被自动的取消。
        super.onDestroy()
    }

    private fun loadDataFromUI() = launch {
        val ioData = async(Dispatchers.IO){
            httpGetInfo()
        }
        val data = ioData.await()
        tvText.text = data
    }

    suspend fun httpGetInfo():String{
        delay(2000)
        return "Hello Coroutine!"
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun delayLoad() = launch {

        val defer1 = async(Dispatchers.IO){
            G.elog("work1 at thread:${Thread.currentThread().name}, timesecond:${Instant.now().epochSecond}")
            httpGetWork1()
        }
        val defer2 = async(Dispatchers.IO){
            G.elog("work2 at thread:${Thread.currentThread().name}, timesecond:${Instant.now().epochSecond}")
            httpGetWork2()
        }
        tvWork1.text = defer1.await()
        tvWork2.text  = defer2.await()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    suspend fun httpGetWork1():String{
        delay(3000L)
        return "This is work1, time:${Instant.now().epochSecond}"
    }

    @RequiresApi(Build.VERSION_CODES.O)
    suspend fun httpGetWork2():String{
        delay(3000L)
        return "This is work2,time:${Instant.now().epochSecond}"
    }

    override fun hideActionBar() = false
}